/* eslint-disable */
/*
 * @Date: 2022-09-12
 * @LastEditors: zhx
 * @LastEditTime: 2022-09-12
 */
import Vue from 'vue'
import store from '@/store'
import axios from 'axios'
// import qs from 'qs'
import { setByCookie, getByCookie, removeByCookie } from '@/utils/token'
import { Message, Loading } from 'element-ui'
import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils";
import { saveAs } from 'file-saver'
import moment from 'moment'
var uuid = require('node-uuid')
var md5 = require('md5')

// 是否显示重新登录
export let isRelogin = {
	show: false
}

const service = axios.create({
	timeout: 30000,
	xsrfCookieName: 'XSRF-COOKIE',
	xsrfHeaderName: 'X-XSRF-HEADER'
})

let isRefreshing = false // 是否正在刷新 token
let requests = [] // 待重发请求数组

service.interceptors.request.use(function(config) {
	// 在发送请求之前做些什么
	// console.log('配置成功:', config)
	return config
}, function(error) {
	// 对请求错误做些什么
	// console.log('配置失败:', error)
	return Promise.reject(error)
})

service.interceptors.response.use(function(response) {
	// 对响应数据做点什么
	// console.log('响应成功:', response.status)
	// Message({ message: '请求成功', type: 'success', center: true })
	return response.data
}, function(error) {
	console.log(error)
	// 对响应错误做点什么
	let { message } = error
	if (message == "Network Error") {
		message = "后端接口连接异常"
	} else if (message.includes("timeout")) {
		message = "系统接口请求超时"
	} else if (message.includes("Request failed with status code")) {
		message = "系统接口" + message.substr(message.length - 3) + "异常"
	}

	if (error.response.status === 401 && !error.config.url.includes('/auth/refresh')) {
		removeByCookie("authorization")
		window.location.href = "/login"
		// const { config } = error
		// if (!isRefreshing) {
		//     isRefreshing = true
		//     return commonRequest({
		// 	url: "/auth/refresh",
		// 	method: "POST",
		// 	body: {
		// 		refresh_token: getRefreshToken()
		// 	}
		// }).then(res=> {
		//         const { access_token } = res.data
		//         setByCookie(access_token)
		//         service.defaults.headers['authorization'] = getByCookie('Authorize')

		//         // token 刷新后将数组的方法重新执行
		//         requests.forEach((cb) => cb(access_token))
		//         requests = [] // 重新请求完清空
		//         return service(config)
		//     }).catch(err => {
		//         console.log('抱歉，您的登录状态已失效，请重新登录！')
		//         return Promise.reject(err)
		//     }).finally(() => {
		//         isRefreshing = false
		//     })
		// } else {
		//     // 返回未执行 resolve 的 Promise
		//     return new Promise(resolve => {
		//         // 用函数形式将 resolve 存入，等待刷新后再执行
		//         requests.push(token => {
		//             service.defaults.headers['authorization'] = token
		//             resolve(service(config))
		//         })  
		//     })
		// }
	}

	// console.log('响应失败:', error.response.status)
	switch (error.response.status) {
		case 400:
			Message({ message: '参数错误', type: 'error', center: true, showClose: true })
			break
		case 401:
			Message({ message: '未授权', type: 'error', center: true, showClose: true })
			break
		case 402:
			Message({ message: '名称重复', type: 'error', center: true, showClose: true })
			break
		case 403:
			Message({ message: '拒绝访问', type: 'error', center: true, showClose: true })
			break
		case 404:
			Message({ message: `请求地址出错: ${error.response.config.url}`, type: 'error', center: true, showClose: true })
			break
		case 408:
			Message({ message: '请求超时', type: 'error', center: true, showClose: true })
			break
		case 500:
			Message({ message: '服务端错误', type: 'error', center: true, showClose: true })
			break
		case 501:
			Message({ message: '服务未实现', type: 'error', center: true, showClose: true })
			break
		case 502:
			Message({ message: '网关错误', type: 'error', center: true, showClose: true })
			break
		case 503:
			Message({ message: '服务不可用', type: 'error', center: true, showClose: true })
			break
		case 504:
			Message({ message: '网关超时', type: 'error', center: true, showClose: true })
			break
		case 505:
			Message({ message: 'HTTP版本不受支持', type: 'error', center: true, showClose: true })
			break
		default:
			Message({ message: message, type: 'error', duration: 5000, center: true })
			break
	}
	return Promise.reject(error)
})

let downloadLoadingInstance
// 通用下载方法
export function download(url, params, filename) {
	downloadLoadingInstance = Loading.service({
		text: "正在下载数据，请稍候",
		spinner: "el-icon-loading",
		background: "rgba(0, 0, 0, 0.7)",
	})
	return service.post(url, params, {
		transformRequest: [(params) => {
			return tansParams(params)
		}],
		headers: {
			'Content-Type': 'application/x-www-form-urlencoded'
		},
		responseType: 'blob'
	}).then(async (data) => {
		const isLogin = await blobValidate(data);
		if (isLogin) {
			const blob = new Blob([data])
			saveAs(blob, filename)
		} else {
			const resText = await data.text();
			const rspObj = JSON.parse(resText);
			const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default']
			Message.error(errMsg);
		}
		downloadLoadingInstance.close();
	}).catch((r) => {
		console.error(r)
		Message.error('下载文件出现错误，请联系管理员！')
		downloadLoadingInstance.close();
	})
}

/**
 * 取消请求
 */
export function cancelRequest(msg = '') {
	let cancelArr = window.axiosCancel
	cancelArr = cancelArr || []
	cancelArr.forEach((ele, index) => {
		ele.cancel(msg || '登录过期或已失效, 请重新登录')
	})
	window.axiosCancel = []
}

/**
 * 通用API接口
 */
export function commonRequest(options) {
	const { url, method, urlParams, body, header } = options
	if (method.toUpperCase() === 'POST') {
		loading = Loading.service({
			lock: true,
			text: 'Loading',
			spinner: 'el-icon-loading',
			background: 'rgba(0, 0, 0, 0.7)'
		});
	} else {
		loading = ''
	}

	const appId = 'ApiPost_Test'
	const guid = uuid.v4()
	const appSecret = 'glAYqL8z4BUU4MnW'
	let signBody = ''
	if (body) {
		signBody = JSON.stringify(body)
	}
	const time = moment().format('YYYY-MM-DD HH:mm:ss')
	const sign = md5(appId + time + guid + signBody + appSecret)
	service.defaults.headers['appId'] = 'ApiPost_Test'
	service.defaults.headers['time'] = time
	service.defaults.headers['guid'] = guid
	service.defaults.headers['sign'] = sign
	service.defaults.headers['authorization'] = getByCookie('Authorize')
	service.defaults.headers['Content-Type'] = 'application/json'
	const baseUrl = Vue.prototype.$systemConfig.BaseUrl

	const params = {}
	let cancelToken = {}
	cancelToken = new axios.CancelToken(cancel => {
		if (!window.axiosCancel) {
			window.axiosCancel = []
		}
		
		if (url.indexOf('GetOperatorInfo') === -1) {
			window.axiosCancel.push({
				cancel
			})
		}

	})

	// console.log(window.axiosCancel)

	if (urlParams) {
		Object.assign(params, urlParams)
	}

	let data
	if (body) {
		data = JSON.stringify(body)
		// data = qs.stringify(body)
	}

	if (header) {
		service.defaults.headers = header
	}

	return service({
		url: baseUrl + url,
		method,
		params,
		data
	})

}